package chapter11_3_concurrentHashMap;

import cn.hutool.json.JSONUtil;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 虽然是并发安全的组件,但是如果使用不当,仍会导致错误
 * @author Summerday
 */
public class TestMap2 {
    // key 为topic value 为设备列表
    static ConcurrentHashMap<String, List<String>> map = new ConcurrentHashMap<>();

    public static void main(String[] args) {
        Thread threadOne = new Thread(()->{
           List<String> list1 = new ArrayList<>();
           list1.add("device1");
           list1.add("device2");
            List<String> oldList = map.putIfAbsent("topic1", list1);
            if(null != oldList){
                oldList.addAll(list1);
            }
            System.out.println(JSONUtil.toJsonStr(map));
        });

        Thread threadTwo = new Thread(()->{
            List<String> list1 = new ArrayList<>();
            list1.add("device11");
            list1.add("device22");
            List<String> oldList = map.putIfAbsent("topic1", list1);
            if(null != oldList){
                oldList.addAll(list1);
            }
            System.out.println(JSONUtil.toJsonStr(map));
        });

        Thread threadThree = new Thread(()->{
            List<String> list1 = new ArrayList<>();
            list1.add("device111");
            list1.add("device222");
            List<String> oldList = map.putIfAbsent("topic3", list1);
            if(null != oldList){
                oldList.addAll(list1);
            }
            System.out.println(JSONUtil.toJsonStr(map));
        });

        threadOne.start();
        threadTwo.start();
        threadThree.start();

    }

}
